package com.outdoor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.outdoor.exception.BusinessException;
import com.outdoor.model.entity.User;
import com.outdoor.mapper.UserMapper;
import com.outdoor.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户服务实现
 * 
 * @author OutdoorTeam
 * @date 2025-05-18
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    @Override
    public User createUser(User user) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("username", user.getUsername());
        if (userMapper.selectCount(query) > 0) {
            throw new BusinessException("USERNAME_EXISTS", "用户名已存在");
        }
        user.setTripsCount(0);
        
        // 将List转为逗号分隔的字符串（已由实体类自动处理）
        // interestsList会自动更新interests字段
        
        userMapper.insert(user);
        log.info("创建用户成功: {}", user.getUsername());
        return user;
    }

    @Override
    public User getUserById(Long id) {
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new BusinessException("USER_NOT_FOUND", "用户不存在");
        }
        
        // 实体类会自动处理字符串到List的转换
        // 调用getInterestsList()和getEquipmentList()方法即可获取List
        
        return user;
    }

    @Override
    public User getUserByUsername(String username) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("username", username);
        User user = userMapper.selectOne(query);
        if (user == null) {
            throw new BusinessException("USER_NOT_FOUND", "用户不存在");
        }
        return user;
    }

    @Override
    public User updateUser(Long id, User userUpdate) {
        User user = getUserById(id);
        if (userUpdate.getName() != null) {
            user.setName(userUpdate.getName());
        }
        if (userUpdate.getBio() != null) {
            user.setBio(userUpdate.getBio());
        }
        if (userUpdate.getInterestsList() != null) {
            user.setInterestsList(userUpdate.getInterestsList());
        }
        if (userUpdate.getEquipmentList() != null) {
            user.setEquipmentList(userUpdate.getEquipmentList());
        }
        if (userUpdate.getWechatId() != null) {
            user.setWechatId(userUpdate.getWechatId());
        }
        userMapper.updateById(user);
        log.info("更新用户成功: {}", user.getUsername());
        return user;
    }

    @Override
    public void deleteUser(Long id) {
        User user = getUserById(id);
        userMapper.deleteById(id);
        log.info("删除用户成功: {}", user.getUsername());
    }

    @Override
    public IPage<User> listUsers(Page<User> page) {
        return userMapper.selectPage(page, null);
    }

    @Override
    public void incrementTripsCount(Long userId) {
        User user = getUserById(userId);
        user.setTripsCount(user.getTripsCount() + 1);
        userMapper.updateById(user);
        log.info("增加用户行程计数: {}，当前计数: {}", user.getUsername(), user.getTripsCount());
    }

    @Override
    public List<User> getUsersByIds(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return new ArrayList<>();
        }
        return userMapper.selectBatchIds(ids);
    }

    /**
     * 获取用户兴趣爱好列表
     * 
     * @param interests 兴趣爱好字符串
     * @return 兴趣爱好列表
     */
    public List<String> getInterestsList(String interests) {
        return stringToList(interests);
    }

    /**
     * 获取用户装备列表
     * 
     * @param equipment 装备字符串
     * @return 装备列表
     */
    public List<String> getEquipmentList(String equipment) {
        return stringToList(equipment);
    }

    /**
     * 将列表转为逗号分隔的字符串
     * 
     * @param list 字符串列表
     * @return 逗号分隔字符串
     */
    public String listToString(List<String> list) {
        if (list == null || list.isEmpty()) {
            return "";
        }
        return String.join(",", list);
    }
    
    /**
     * 将逗号分隔的字符串转为List
     */
    private List<String> stringToList(String str) {
        if (str == null || str.isEmpty()) {
            return List.of();
        }
        return Arrays.stream(str.split(","))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .collect(Collectors.toList());
    }
}